package com.sun.controller.admin;

import com.alibaba.fastjson.JSON;
import com.sun.pojo.RoomType;
import com.sun.service.RoomTypeService;
import com.sun.utils.DataGridViewResult;
import com.sun.utils.SystemConstant;
import com.sun.utils.UUIDutiles;
import com.sun.vo.RoomTypeVo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin/file")
public class FileUploadController {

    @RequestMapping("/uploadFile")
    public String uploadFile(MultipartFile file) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        // 判断传入文件是否为空
        if (!file.isEmpty()) {
            // 获取文件上传地址
            String path = "D:/store/hotel/upload/";
            // 获取上传文件名称
            String originalFilename = file.getOriginalFilename();
            // 获取上传文件后缀
            String extension = FilenameUtils.getExtension(originalFilename);
            // 重命名原文件
            String newFileName = UUIDutiles.getUuid() + "." + extension;
            // 创建日期文件夹
            String dirName = new SimpleDateFormat("yyyyMMdd").format(new Date());
            // 组装最终文件名
            String finalFileName = dirName + "/" + newFileName;

            // 创建文件对象
            File fileO = new File(path, finalFileName);
            // 判断目录是否存在，不存在则创建
            if (!fileO.getParentFile().exists()) {
                fileO.getParentFile().mkdirs();
            }

            try {
                file.transferTo(fileO);
                map.put("code",0);
                map.put("msg","上传成功!");
                Map dataMap=new HashMap<String,Object>();
                dataMap.put("src","/hotel/upload/"+finalFileName);
                map.put("data",dataMap);
                map.put("imagePath",finalFileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return JSON.toJSONString(map);
    }

}
